package com.example.routeplansystem.algorithm;

import com.example.routeplansystem.constant.ResponseStatus;
import com.example.routeplansystem.constant.RunningProcess;
import com.example.routeplansystem.dao.FinalSolutionDao;
import com.example.routeplansystem.define.FinalSolutionCode;
import com.example.routeplansystem.entity.po.FinalSolution;
import com.example.routeplansystem.entity.po.NodePojo;
import com.example.routeplansystem.entity.po.Solution;
import com.example.routeplansystem.entity.po.VehicleMessage;
import com.example.routeplansystem.exception.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.rmi.ServerException;
import java.util.List;
import java.util.Map;


/**
 * @Author lucong
 * @Date 2022/5/17
 * @Description
 */
@Component
public class AlgorithmFactory {

    @Autowired
    private Map<String, Algorithm> algorithmMap;

    @Autowired
    private FinalSolutionDao finalSolutionDao;

    public String getAlgorithmName(int key) {
        AlgorithmEnum[] enums = AlgorithmEnum.values();
        if (key < 0) return "用户导入";
        if (key >= enums.length) return "不存在该算法";
        return enums[key].name;
    }

    public Algorithm getAlgorithm(int key) throws ServerException {
        AlgorithmEnum[] enums = AlgorithmEnum.values();
        if (key < 0 || key >= enums.length) throw new ServerException("算法不存在!");
        String algorithmName = enums[key].name();
        return algorithmMap.get(algorithmName);
    }

    public List<Solution> executeAlgorithm(List<NodePojo> nodes, List<NodePojo> centerNodes,
                                           List<VehicleMessage> vehicles, FinalSolution fs, int questionId) throws ServerException {
        Algorithm algorithm = getAlgorithm(fs.getVersion());
        if (RunningProcess.isRunning.flag) {
            throw new ServiceException("当前有算法正在运行");
        }
        List<Solution> solutions = null;
        try {
            RunningProcess.isRunning.setFlag(true);
            finalSolutionDao.updateStatusCodeByFinalSolutionId(fs.getFinalSolutionId(), FinalSolutionCode.PREPARE_MATRIX.getCode());
            algorithm.checkMatrix(questionId,fs.getFinalSolutionId());
            finalSolutionDao.updateStatusCodeByFinalSolutionId(fs.getFinalSolutionId(), FinalSolutionCode.CALCULATE.getCode());
            solutions = algorithm.getSolution(nodes, centerNodes, vehicles, fs);
            finalSolutionDao.updateStatusCodeByFinalSolutionId(fs.getFinalSolutionId(), FinalSolutionCode.SUCCESS.getCode());
        } catch (Exception e) {
            finalSolutionDao.updateStatusCodeByFinalSolutionId(fs.getFinalSolutionId(), FinalSolutionCode.DEFAULT.getCode());
            throw new ServiceException("计算异常,msg:" + e.getMessage());
        } finally {
            RunningProcess.isRunning.setFlag(false);
        }
        return solutions;
    }

}

